import random
import os
import threading
import queue
import time
import subprocess
import sys

#检查依赖
def check_and_install_dependencies():
    """检查所需依赖"""
    print("🔍 检查依赖是否安装...")
    required_packages = ["pillow", "tqdm"]
    missing_packages = []
    
    for pkg in required_packages:
        try:
            __import__(pkg)
        except ImportError:
            missing_packages.append(pkg)
    
    if missing_packages:
        print(f"⚠️  缺失依赖：{', '.join(missing_packages)}，开始自动安装...")
        try:
            # 静默安装
            subprocess.check_call(
                [sys.executable, "-m", "pip", "install", *missing_packages, "--no-cache-dir", "-q"],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL
            )
            print("✅ Python依赖安装完成")
        except subprocess.CalledProcessError as e:
            print(f"❌ Python依赖安装失败：{e}")
            sys.exit(1)
    
    #仅Termux环境
    if "com.termux" in os.environ.get("PREFIX", ""):
        try:
            subprocess.check_call(
                ["pkg", "list-installed", "libjpeg-turbo", "zlib"],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL
            )
        except subprocess.CalledProcessError:
            print("⚠️  缺失系统依赖，开始安装...")
            try:
                subprocess.check_call(
                    ["pkg", "update", "-y", "-qq"],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL
                )
                subprocess.check_call(
                    ["pkg", "install", "libjpeg-turbo", "zlib", "-y", "-qq"],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL
                )
                print("✅ 系统依赖安装完成")
            except subprocess.CalledProcessError as e:
                print(f"❌ 系统依赖安装失败：{e}")
                sys.exit(1)
    
    print("✅ 所有依赖已就绪\n")

check_and_install_dependencies()

from PIL import Image, ImageDraw, ImageFont
from tqdm import tqdm

BACKGROUND_IMAGE = "AG.png"
OUTPUT_DIR = "a"
FONT_PATH = "/system/fonts/DroidSans.ttf"
if not os.path.exists(FONT_PATH):
    FONT_PATH = "/system/fonts/NotoSansSC-Regular.ttf"
CAPTCHA_SIZE = (600, 240)
CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
CHAR_COUNT = 5
THREAD_COUNT = 4
task_queue = queue.Queue()
generated_set = set()
lock = threading.Lock()

success_count = 0
fail_count = 0
total_size = 0

def generate_single_captcha(pbar):
    """验证码生成"""
    width, height = CAPTCHA_SIZE
    while True:
        try:
            task_queue.get(timeout=1)
            
            captcha_text = None
            while True:
                temp_text = "".join(random.sample(CHAR_SET, CHAR_COUNT))
                with lock:
                    if temp_text not in generated_set:
                        generated_set.add(temp_text)
                        captcha_text = temp_text
                        break
            
            img_filename = f"{captcha_text}.png"
            img_path = os.path.join(OUTPUT_DIR, img_filename)
            
            if os.path.exists(BACKGROUND_IMAGE):
                bg = Image.open(BACKGROUND_IMAGE).convert("RGBA")
                bg = bg.resize((width, height), Image.Resampling.LANCZOS)
                img = Image.new("RGBA", (width, height), (255, 255, 255, 255))
                img.paste(bg, (0, 0), bg)
            else:
                img = Image.new("RGB", (width, height), (245, 245, 245))
            
            draw = ImageDraw.Draw(img)
            font = ImageFont.truetype(FONT_PATH, size=140)  #字体
            
            for i, char in enumerate(captcha_text):
                color = (random.randint(20, 80), random.randint(20, 80), random.randint(20, 80), random.randint(180, 220))
                x = 70 + i * 105 + random.randint(-8, 8)
                y = random.randint(10, 50)
                draw.text((x, y), char, font=font, fill=color)
            
            for _ in range(6):
                line_color = (random.randint(90, 180), random.randint(90, 180), random.randint(90, 180))
                start = (random.randint(0, width//3), random.randint(0, height))
                end = (random.randint(width//2, width), random.randint(0, height))
                draw.line([start, end], fill=line_color, width=5)
            
            for _ in range(4):
                rect_color = (random.randint(70, 160), random.randint(70, 160), random.randint(70, 160))
                x1 = random.randint(40, width//2)
                y1 = random.randint(40, height//2)
                x2 = random.randint(width//2, width-40)
                y2 = random.randint(height//2, height-40)
                draw.rectangle([x1, y1, x2, y2], outline=rect_color, width=5)
            
            if img.mode == "RGBA":
                img = img.convert("RGB")
            img.save(img_path, quality=100, optimize=False)
            
            file_size = os.path.getsize(img_path)
            with lock:
                global success_count, total_size
                success_count += 1
                total_size += file_size
            
            pbar.update(1)
            task_queue.task_done()
        
        except queue.Empty:
            break
        except Exception as e:
            with lock:
                global fail_count
                fail_count += 1
            pbar.update(1)
            task_queue.task_done()

if __name__ == "__main__":
    while True:
        try:
            count_input = input("请输入验证码数量：")
            generate_count = int(count_input)
            if generate_count > 0:
                break
            else:
                print("❌ 数量必须是整数，请重新输入")
        except ValueError:
            print("❌ 输入无效，请输入数字")
    
    if not os.path.exists(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR)
    
    for _ in range(generate_count):
        task_queue.put(1)
    
    print(f"\n🚀 启动 {THREAD_COUNT} 个线程，超高清模式生成...")
    start_time = time.time()
    
    with tqdm(total=generate_count, desc="生成进度", unit="个", ncols=80) as pbar:
        threads = []
        for i in range(THREAD_COUNT):
            t = threading.Thread(target=generate_single_captcha, args=(pbar,), name=f"Thread-{i+1}")
            t.daemon = True
            t.start()
            threads.append(t)
        
        for t in threads:
            t.join()
    
    total_time = round(time.time() - start_time, 2)
    total_size_mb = round(total_size / (1024 * 1024), 2)
    
    print("\n" + "="*50)
    print("生成任务完成！")
    print("="*50)
    print(f"总任务数：{generate_count} 个")
    print(f"成功生成：{success_count} 个")
    print(f"生成失败：{fail_count} 个")
    print(f"单个分辨率：{CAPTCHA_SIZE[0]}×{CAPTCHA_SIZE[1]} | 字体大小：140号")
    print(f"总文件大小：{total_size_mb} MB")
    print(f"总耗时：{total_time} 秒")
    print(f"保存目录：{os.path.abspath(OUTPUT_DIR)}")
    print("="*50)
